<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>管理员后台 - 助农精准扶贫平台</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
        <div class="container-fluid">
            <a class="navbar-brand" href="#">管理员后台</a>
            <div class="navbar-nav ms-auto">
                <a class="nav-link text-white" href="#" onclick="logout()">退出</a>
            </div>
        </div>
    </nav>

    <div class="container-fluid">
        <div class="row">
            <nav class="col-md-2 d-md-block bg-light sidebar py-3">
                <div class="position-sticky">
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link active" href="#" onclick="showSection('overview')">数据统计</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="#" onclick="showSection('users')">用户管理</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="#" onclick="showSection('products')">商品审核</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="#" onclick="showSection('categories')">分类管理</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="#" onclick="showSection('notices')">公告管理</a>
                        </li>
                    </ul>
                </div>
            </nav>

            <main class="col-md-10 ms-sm-auto px-md-4 py-4">
                <div id="overviewSection">
                    <h2>数据统计</h2>
                    <div class="row mt-4">
                        <div class="col-md-3">
                            <div class="card text-center">
                                <div class="card-body">
                                    <h5 class="card-title">总用户数</h5>
                                    <h2 id="totalUsers">0</h2>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="card text-center">
                                <div class="card-body">
                                    <h5 class="card-title">农户数</h5>
                                    <h2 id="totalFarmers">0</h2>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="card text-center">
                                <div class="card-body">
                                    <h5 class="card-title">商品数</h5>
                                    <h2 id="totalProducts">0</h2>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="card text-center">
                                <div class="card-body">
                                    <h5 class="card-title">总销售额</h5>
                                    <h2 id="totalSales">¥0</h2>
                                </div>
                            </div>
                        </div>
                    </div>

                    <h3 class="mt-5">农户销售排行</h3>
                    <div id="farmerSalesRank" class="mt-3"></div>
                </div>

                <div id="usersSection" style="display: none;">
                    <h2>用户管理</h2>
                    <div id="userList" class="mt-3"></div>
                </div>

                <div id="productsSection" style="display: none;">
                    <h2>商品审核</h2>
                    <div id="pendingProductList" class="mt-3"></div>
                </div>

                <div id="categoriesSection" style="display: none;">
                    <h2>分类管理</h2>
                    <button class="btn btn-primary mb-3" onclick="showAddCategoryForm()">添加分类</button>
                    <div id="addCategoryForm" style="display: none;" class="mb-3">
                        <div class="card">
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-md-6">
                                        <input type="text" class="form-control" id="categoryName" placeholder="分类名称">
                                    </div>
                                    <div class="col-md-4">
                                        <input type="number" class="form-control" id="categorySortOrder" placeholder="排序" value="0">
                                    </div>
                                    <div class="col-md-2">
                                        <button class="btn btn-success" onclick="addCategory()">保存</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div id="categoryList" class="mt-3"></div>
                </div>

                <div id="noticesSection" style="display: none;">
                    <h2>公告管理</h2>
                    <button class="btn btn-primary mb-3" onclick="showAddNoticeForm()">发布公告</button>
                    <div id="addNoticeForm" style="display: none;" class="mb-3">
                        <div class="card">
                            <div class="card-body">
                                <div class="mb-3">
                                    <label>标题</label>
                                    <input type="text" class="form-control" id="noticeTitle" placeholder="公告标题">
                                </div>
                                <div class="mb-3">
                                    <label>内容</label>
                                    <textarea class="form-control" id="noticeContent" rows="4" placeholder="公告内容"></textarea>
                                </div>
                                <div class="mb-3">
                                    <label>类型</label>
                                    <select class="form-control" id="noticeType">
                                        <option value="announcement">公告</option>
                                        <option value="news">新闻</option>
                                        <option value="policy">政策</option>
                                    </select>
                                </div>
                                <button class="btn btn-success" onclick="addNotice()">发布</button>
                                <button class="btn btn-secondary" onclick="$('#addNoticeForm').hide()">取消</button>
                            </div>
                        </div>
                    </div>
                    <div id="noticeList" class="mt-3"></div>
                </div>
            </main>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        $(document).ready(function() {
            const token = localStorage.getItem('token');
            if (!token) {
                alert('请先登录');
                window.location.href = '/login.html';
                return;
            }
            loadOverview();
        });

        function showSection(section) {
            $('#overviewSection, #usersSection, #productsSection, #categoriesSection, #noticesSection').hide();
            if (section === 'overview') {
                $('#overviewSection').show();
                loadOverview();
            } else if (section === 'users') {
                $('#usersSection').show();
                loadUsers();
            } else if (section === 'products') {
                $('#productsSection').show();
                loadPendingProducts();
            } else if (section === 'categories') {
                $('#categoriesSection').show();
                loadCategories();
            } else if (section === 'notices') {
                $('#noticesSection').show();
                loadNotices();
            }
        }

        function loadOverview() {
            const token = localStorage.getItem('token');

            $.ajax({
                url: '/api/statistics/overview',
                method: 'GET',
                headers: { 'Authorization': 'Bearer ' + token },
                success: function(response) {
                    if (response.code === 200) {
                        const data = response.data;
                        $('#totalUsers').text(data.totalUsers);
                        $('#totalFarmers').text(data.totalFarmers);
                        $('#totalProducts').text(data.totalProducts);
                        $('#totalSales').text('¥' + data.totalSales);
                    }
                }
            });

            $.ajax({
                url: '/api/statistics/farmer-sales',
                method: 'GET',
                headers: { 'Authorization': 'Bearer ' + token },
                success: function(response) {
                    if (response.code === 200) {
                        renderFarmerSales(response.data);
                    }
                }
            });
        }

        function renderFarmerSales(sales) {
            const container = $('#farmerSalesRank');
            container.empty();

            if (sales.length === 0) {
                container.append('<p class="text-muted">暂无数据</p>');
                return;
            }

            const table = `
                <table class="table">
                    <thead>
                        <tr>
                            <th>排名</th>
                            <th>农户姓名</th>
                            <th>销售额</th>
                        </tr>
                    </thead>
                    <tbody id="salesTableBody"></tbody>
                </table>
            `;
            container.html(table);

            sales.slice(0, 10).forEach((item, index) => {
                $('#salesTableBody').append(`
                    <tr>
                        <td>${index + 1}</td>
                        <td>${item.farmerName}</td>
                        <td>¥${item.sales}</td>
                    </tr>
                `);
            });
        }

        function loadUsers() {
            const token = localStorage.getItem('token');

            $.ajax({
                url: '/api/users/list',
                method: 'GET',
                headers: { 'Authorization': 'Bearer ' + token },
                data: { page: 1, size: 50 },
                success: function(response) {
                    if (response.code === 200) {
                        renderUsers(response.data.records);
                    }
                }
            });
        }

        function renderUsers(users) {
            const container = $('#userList');
            container.empty();

            const table = `
                <table class="table">
                    <thead>
                        <tr>
                            <th>用户名</th>
                            <th>真实姓名</th>
                            <th>角色</th>
                            <th>电话</th>
                            <th>状态</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="userTableBody"></tbody>
                </table>
            `;
            container.html(table);

            users.forEach(user => {
                const roleText = { 'farmer': '农户', 'buyer': '消费者', 'admin': '管理员' }[user.role];
                const statusText = user.status === 1 ? '启用' : '禁用';
                $('#userTableBody').append(`
                    <tr>
                        <td>${user.username}</td>
                        <td>${user.realName}</td>
                        <td>${roleText}</td>
                        <td>${user.phone}</td>
                        <td>${statusText}</td>
                        <td>
                            ${user.status === 1 ? 
                                `<button class="btn btn-sm btn-warning" onclick="toggleUserStatus(${user.id}, 0)">禁用</button>` :
                                `<button class="btn btn-sm btn-success" onclick="toggleUserStatus(${user.id}, 1)">启用</button>`
                            }
                        </td>
                    </tr>
                `);
            });
        }

        function toggleUserStatus(userId, status) {
            const token = localStorage.getItem('token');
            
            $.ajax({
                url: '/api/users/' + userId + '/status',
                method: 'PUT',
                headers: { 'Authorization': 'Bearer ' + token },
                contentType: 'application/json',
                data: JSON.stringify({ status: status }),
                success: function(response) {
                    if (response.code === 200) {
                        alert('操作成功');
                        loadUsers();
                    }
                }
            });
        }

        function loadPendingProducts() {
            const token = localStorage.getItem('token');

            $.ajax({
                url: '/api/products/pending',
                method: 'GET',
                headers: { 'Authorization': 'Bearer ' + token },
                data: { page: 1, size: 50 },
                success: function(response) {
                    if (response.code === 200) {
                        renderPendingProducts(response.data.records);
                    }
                }
            });
        }

        function renderPendingProducts(products) {
            const container = $('#pendingProductList');
            container.empty();

            if (products.length === 0) {
                container.append('<p class="text-muted">暂无待审核商品</p>');
                return;
            }

            products.forEach(p => {
                const card = `
                    <div class="card mb-3">
                        <div class="card-body">
                            <h5>${p.name}</h5>
                            <p>价格：¥${p.price}/${p.unit} | 库存：${p.stock} | 产地：${p.region}</p>
                            <p>${p.description || ''}</p>
                            <button class="btn btn-sm btn-success" onclick="approveProduct(${p.id}, 'approved')">通过</button>
                            <button class="btn btn-sm btn-danger" onclick="approveProduct(${p.id}, 'rejected')">拒绝</button>
                        </div>
                    </div>
                `;
                container.append(card);
            });
        }

        function approveProduct(id, status) {
            const token = localStorage.getItem('token');
            
            $.ajax({
                url: '/api/products/' + id + '/approve',
                method: 'PUT',
                headers: { 'Authorization': 'Bearer ' + token },
                contentType: 'application/json',
                data: JSON.stringify({ status: status }),
                success: function(response) {
                    if (response.code === 200) {
                        alert('审核成功');
                        loadPendingProducts();
                    }
                }
            });
        }

        function loadCategories() {
            $.ajax({
                url: '/api/categories/tree',
                method: 'GET',
                success: function(response) {
                    if (response.code === 200) {
                        renderCategories(response.data);
                    }
                }
            });
        }

        function renderCategories(categories) {
            const container = $('#categoryList');
            container.empty();

            const table = `
                <table class="table">
                    <thead>
                        <tr>
                            <th>分类名称</th>
                            <th>排序</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="categoryTableBody"></tbody>
                </table>
            `;
            container.html(table);

            categories.forEach(cat => {
                $('#categoryTableBody').append(`
                    <tr>
                        <td>${cat.name}</td>
                        <td>${cat.sortOrder}</td>
                        <td>
                            <button class="btn btn-sm btn-danger" onclick="deleteCategory(${cat.id})">删除</button>
                        </td>
                    </tr>
                `);
            });
        }

        function showAddCategoryForm() {
            $('#addCategoryForm').toggle();
        }

        function addCategory() {
            const token = localStorage.getItem('token');
            const data = {
                name: $('#categoryName').val(),
                parentId: 0,
                sortOrder: parseInt($('#categorySortOrder').val())
            };

            $.ajax({
                url: '/api/categories',
                method: 'POST',
                headers: { 'Authorization': 'Bearer ' + token },
                contentType: 'application/json',
                data: JSON.stringify(data),
                success: function(response) {
                    if (response.code === 200) {
                        alert('添加成功');
                        $('#categoryName').val('');
                        $('#categorySortOrder').val('0');
                        $('#addCategoryForm').hide();
                        loadCategories();
                    }
                }
            });
        }

        function deleteCategory(id) {
            if (!confirm('确定要删除这个分类吗？')) return;

            const token = localStorage.getItem('token');
            $.ajax({
                url: '/api/categories/' + id,
                method: 'DELETE',
                headers: { 'Authorization': 'Bearer ' + token },
                success: function(response) {
                    if (response.code === 200) {
                        alert('删除成功');
                        loadCategories();
                    }
                }
            });
        }

        function loadNotices() {
            const token = localStorage.getItem('token');

            $.ajax({
                url: '/api/notices/all',
                method: 'GET',
                headers: { 'Authorization': 'Bearer ' + token },
                data: { page: 1, size: 50 },
                success: function(response) {
                    if (response.code === 200) {
                        renderNotices(response.data.records);
                    }
                }
            });
        }

        function renderNotices(notices) {
            const container = $('#noticeList');
            container.empty();

            if (notices.length === 0) {
                container.append('<p class="text-muted">暂无公告</p>');
                return;
            }

            const table = `
                <table class="table">
                    <thead>
                        <tr>
                            <th>标题</th>
                            <th>类型</th>
                            <th>状态</th>
                            <th>创建时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="noticeTableBody"></tbody>
                </table>
            `;
            container.html(table);

            notices.forEach(notice => {
                const typeText = { 'announcement': '公告', 'news': '新闻', 'policy': '政策' }[notice.type];
                const statusText = notice.status === 1 ? '已发布' : '已隐藏';
                $('#noticeTableBody').append(`
                    <tr>
                        <td>${notice.title}</td>
                        <td>${typeText}</td>
                        <td>${statusText}</td>
                        <td>${notice.createTime}</td>
                        <td>
                            <button class="btn btn-sm btn-danger" onclick="deleteNotice(${notice.id})">删除</button>
                        </td>
                    </tr>
                `);
            });
        }

        function showAddNoticeForm() {
            $('#addNoticeForm').toggle();
        }

        function addNotice() {
            const token = localStorage.getItem('token');
            const data = {
                title: $('#noticeTitle').val(),
                content: $('#noticeContent').val(),
                type: $('#noticeType').val()
            };

            if (!data.title || !data.content) {
                alert('请填写完整信息');
                return;
            }

            $.ajax({
                url: '/api/notices',
                method: 'POST',
                headers: { 'Authorization': 'Bearer ' + token },
                contentType: 'application/json',
                data: JSON.stringify(data),
                success: function(response) {
                    if (response.code === 200) {
                        alert('发布成功');
                        $('#noticeTitle').val('');
                        $('#noticeContent').val('');
                        $('#addNoticeForm').hide();
                        loadNotices();
                    }
                }
            });
        }

        function deleteNotice(id) {
            if (!confirm('确定要删除这条公告吗？')) return;

            const token = localStorage.getItem('token');
            $.ajax({
                url: '/api/notices/' + id,
                method: 'DELETE',
                headers: { 'Authorization': 'Bearer ' + token },
                success: function(response) {
                    if (response.code === 200) {
                        alert('删除成功');
                        loadNotices();
                    }
                }
            });
        }

        function logout() {
            localStorage.removeItem('token');
            localStorage.removeItem('user');
            window.location.href = '/login.html';
        }
    </script>
</body>
</html>

